package com.dcloud.file.util;

import cn.hutool.core.io.FileUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;

public class CustomFileUtil {
    /**
     * 生成文件名称
     * Timestamp + '-' + UUID + '-' + 原文件名
     * @param filename
     * @return
     */
    public static String getFilename(String filename) {
        return System.currentTimeMillis() + "-" +
                (UUID.randomUUID().toString().replaceAll("-", "")) + "-" +
                filename;
    }

    /**
     * 根据url读取远程文本内容
     *
     */
    public static String readUrl(String urlStr) {
        StringBuilder sb = new StringBuilder();
        try {
            URL url = new URL(urlStr);
            URLConnection urlConnection = url.openConnection();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                sb.append(str);
                sb.append(System.lineSeparator());
            }
            bufferedReader.close();
        } catch (Exception e) {
            throw new RuntimeException("远程文件读取异常：{}"+urlStr);
        }

        return sb.toString();
    }

    /**
     * @Description: 获取文件后缀
     * @param remoteFilePath
     * @return: String
     * @Author: shijf
     * @Date 2024/4/23 22:39
     */
    public static String getSuffix(String remoteFilePath) {
        if (remoteFilePath.contains(".")) {
            return remoteFilePath.substring(remoteFilePath.lastIndexOf("."));
        }
        return null;
    }

    public static void mkdir(String dir) {
        FileUtil.mkdir(dir);
    }
}
